package lj.courseinterect.rest.resources;

import lj.courseinterect.dao.i.CourseInfoDao;
import lj.courseinterect.dao.i.StudentCourseDao;
import lj.courseinterect.dao.i.StudentDao;
import lj.courseinterect.entity.CourseInfo;
import lj.courseinterect.entity.Student;
import lj.courseinterect.entity.StudentCourse;
import lj.courseinterect.entity.Teacher;
import lj.courseinterect.transfer.OperationTransfer;
import lj.courseinterect.transfer.TokenTransfer;
import lj.courseinterect.transfer.StudentTransfer;
import lj.courseinterect.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.jws.soap.SOAPBinding;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
@Path("/{a:tea|stu}/students")
public class StudentResource
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired// 自动添加填充
    private StudentDao studentDao;

    @Autowired
    private StudentCourseDao studentCourseDao;

    @Autowired
    private CourseInfoDao courseInfoDao;

	@Autowired
	@Qualifier("studentAuthenticationManager")
	private AuthenticationManager authManager;

    /**
     * filter调用获得用户信息
     * @return 用户中介信息
     */
	@GET //查询
	@Produces(MediaType.APPLICATION_JSON) //返回json媒体对象
	public Student getStudent()
	{
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		if (principal instanceof String && ((String) principal).equals("anonymousUser")) {
			return null;
		}
		UserDetails userDetails = (UserDetails) principal;
        Student student = studentDao.findByStuNum(userDetails.getUsername());
        student.setStuPwd("");
		return student;
	}

    @GET //查询
    @Path("/{stuId: [0-9]*$}")
    @Produces(MediaType.APPLICATION_JSON) //返回json媒体对象
    public Student getStudent(@PathParam("stuId") Long stuId)
    {
        Student student = studentDao.find(stuId);
        if(student == null){
            return null;
        }
        student.setStuPwd("");
        return student;
    }

    /**
     *
     * @param stuNum 学生学号
     * @param stuPwd 学生密码
     * @return Token中介类
     */
	@Path("authenticate")
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	public OperationTransfer<TokenTransfer> authenticate(@FormParam("stuNum") String stuNum, @FormParam("stuPwd") String stuPwd)
	{
		UsernamePasswordAuthenticationToken authenticationToken =
				new UsernamePasswordAuthenticationToken(stuNum, stuPwd);
         try{
             Authentication authentication = this.authManager.authenticate(authenticationToken);
             SecurityContextHolder.getContext().setAuthentication(authentication);

             UserDetails userDetails = this.studentDao.loadUserByUsername(stuNum);
             return new OperationTransfer<TokenTransfer>(true, "登陆成功",new TokenTransfer(TokenUtils.createToken(userDetails)));
         } catch (Exception ex){
             return new OperationTransfer<TokenTransfer>(false, "登陆失败");
         }
	}

    /**
     * 根据信息获取roles
     * @param userDetails 用户信息
     * @return 权限
     */
	private Map<String, Boolean> createRoleMap(UserDetails userDetails)
	{
		Map<String, Boolean> roles = new HashMap<String, Boolean>();
		for (GrantedAuthority authority : userDetails.getAuthorities()) {
			roles.put(authority.getAuthority(), Boolean.TRUE);
		}

		return roles;
	}

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public OperationTransfer create(Student student)
    {
        this.logger.info("create(): " + student);

        student.addRole("student");
        student.setStuPwd(passwordEncoder.encode(student.getStuPwd()));

        OperationTransfer operationTransfer;
        student.setStuState(Student.StuState.NORMAL);
        if(this.studentDao.findByStuNum(student.getStuNum()) == null){
            try{
                this.studentDao.save(student);
                operationTransfer = new OperationTransfer(true, "创建用户成功");
            } catch (Exception ex){
                operationTransfer = new OperationTransfer(false, "数据库操作失败");
            }
        } else {
            operationTransfer = new OperationTransfer(false, "学号已存在");
        }

        this.logger.info("create(): " + operationTransfer.toString());
        return operationTransfer;
    }

    public StudentDao getStudentDao() {
        return studentDao;
    }

    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
}